package com.example.shouybl.utils;

import android.widget.BaseAdapter;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.example.shouybl.bean.AppBaseBean;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.RequestParams;
import com.loopj.android.http.TextHttpResponseHandler;


import java.util.List;

import cz.msebera.android.httpclient.Header;

/**
 *
 */
public class AppAsyncTaskHelper {
    private static AppAsyncTaskHelper helper;


    private AsyncHttpClient httpClient;

    private AppAsyncTaskHelper()

    {
        httpClient = new AsyncHttpClient();


    }


    public static AppAsyncTaskHelper getInstance() {
        if (helper == null) {
            helper = new AppAsyncTaskHelper();
        }
        return helper;
    }

    /**
     *
     * @param url
     * @param params
     * @param list
     * @param ptrListView
     * @param adapter
     * @param page
     * @param type
     * @param <T>
     */
    public <T> void post(String url, RequestParams params, final List<T> list, final PullToRefreshListView ptrListView, final BaseAdapter adapter, final int page, final TypeReference<AppBaseBean<T>> type) {
        httpClient.post(url, params, new TextHttpResponseHandler() {
            @Override
            public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {

            }

            @Override
            public void onSuccess(int statusCode, Header[] headers, String responseString) {
                ptrListView.onRefreshComplete();
                //解析数据
                AppBaseBean bean = JSONObject.parseObject(responseString, type);
                if (bean != null && bean.getState().equals("success")) {
                    if (page == 1 && !list.isEmpty()) {
                        list.clear();
                    }
                    list.addAll(bean.getInfo());
                    adapter.notifyDataSetChanged();
                }
            }
        });


    }


}
